#include "dump.h"
#define STRING_TABLE_BUFFER_LEN 1024

ui8 * string_table_load_string( FILE *fp, object_header_t *h, ui32 offset ){
  static ui8 string_table_buffer[ STRING_TABLE_BUFFER_LEN ];
  ui32 cpos;
  ui32 pos = object_header_string_table_position(h) + offset;

    cpos = ftell(fp); // backup the current position
	fseek(fp, pos, SEEK_SET);
    fread(string_table_buffer, STRING_TABLE_BUFFER_LEN, 1, fp);
	fseek(fp, cpos, SEEK_SET); // restore the old position, just in case ... 

	return string_table_buffer;
}

ui32 string_table_get_lenght(FILE *fp, object_header_t *h){
  ui32 cpos, rv;
  ui32 pos = object_header_string_table_position(h);

    cpos = ftell(fp); // backup the current position
	fseek(fp, pos, SEEK_SET);
    fread(&rv, sizeof(int), 1, fp);
	fseek(fp, cpos, SEEK_SET); // restore the old position, just in case ... 

	return rv;
}

ui32 string_table_calc_string_table_lenght(FILE *fp, object_header_t *h){
  ui32 cpos, eof_pos;
  ui32 pos = object_header_string_table_position(h);

    cpos = ftell(fp); // backup the current position
	fseek(fp, 0, SEEK_END);
    eof_pos = ftell(fp); 
	fseek(fp, cpos, SEEK_SET); // restore the old position, just in case ... 

	return eof_pos - pos ;
}

ui32 string_table_set_string_table_lenght(FILE *fp, object_header_t *h){
  ui32 cpos, strlen = string_table_calc_string_table_lenght(fp, h);
  ui32 pos = object_header_string_table_position(h);

    cpos = ftell(fp); // backup the current position
	fseek(fp, pos, SEEK_SET);
	fwrite(&strlen, sizeof(int), 1, fp);
	fseek(fp, cpos, SEEK_SET); // restore the old position, just in case ... 

	return strlen;
}

ui32 string_table_add_string(FILE *fp, object_header_t *h, ui8 *s){
  ui32 cpos, Offset;


    cpos = ftell(fp); // backup the current position
	fseek(fp, 0, SEEK_END);
	fwrite(s, strlen(s) + 1, 1, fp);
	fseek(fp, cpos, SEEK_SET); // restore the old position, just in case ... 

	Offset = string_table_set_string_table_lenght( fp, h );    

	return Offset - strlen(s) -1;
}